package com.yjd.msg.comm.listener;

import com.alibaba.fastjson.JSON;
import com.yjd.comm.msg.MnsMsgInfo;
import com.yjd.comm.util.SpringContextHolder;
import com.yjd.msg.comm.enums.MsgStatusEnum;
import com.yjd.msg.comm.model.MsgDisposeResult;
import org.apache.log4j.Logger;

import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;

/**
 * Created by yjd-wap on 2018/1/24.
 */
public class MnsMsgConsumeTask implements Callable<MsgDisposeResult> {

    private static final Logger logger = Logger.getLogger(MnsMsgConsumeTask.class);

    /**
     * 执行结果
     */
    private MsgDisposeResult result;

    /**
     * 消息监听器服务名称
     */
    private String serviceName;

    /**
     * 消息
     */
    private MnsMsgInfo mnsMsgInfo;

    /**
     * 线程计数器
     */
    private CountDownLatch countDownLatch;

    /**
     * 构造器
     *
     * @param serviceName
     * @param mnsMsgInfo
     */
    public MnsMsgConsumeTask(String serviceName, MnsMsgInfo mnsMsgInfo, CountDownLatch countDownLatch) {
        this.serviceName = serviceName;
        this.mnsMsgInfo = mnsMsgInfo;
        this.countDownLatch = countDownLatch;
        this.result = new MsgDisposeResult(serviceName,MsgStatusEnum.CONSUME_FAIL);
    }

    @Override
    public MsgDisposeResult call() throws Exception {
        try {
            if (this.getMnsMsgInfo() == null || this.getServiceName() == null) {
                return this.getResult();
            }
            DefaulMsgDispose messageListener = SpringContextHolder.getBean(this.getServiceName());
            if (messageListener == null) {
                logger.error("消息处理失败,未找到对应的消息监听器,服务名称：" + this.getServiceName() + "消息信息：" + JSON.toJSONString(mnsMsgInfo));
                //默认为交易失败返回
                return this.getResult();
            }
            this.mnsMsgInfo.setCustomer_name(this.getServiceName());
            messageListener.process(this.getMnsMsgInfo());
            //设置为交易成功
            this.setResult(new MsgDisposeResult(this.getServiceName(),MsgStatusEnum.CONSUME_SUCCESS));
        } catch (Exception e) {
            logger.error("消息处理失败, msgId:" + this.getMnsMsgInfo().getMsg_id()
                    + ",msg_type:"
                    + this.getMnsMsgInfo().getMsg_type() + "异常信息:"
                    + e.getMessage(), e);
        } finally {
            this.countDownLatch.countDown();
        }
        return this.getResult();
    }

    public MsgDisposeResult getResult() {
        return result;
    }

    public void setResult(MsgDisposeResult result) {
        this.result = result;
    }

    public String getServiceName() {
        return serviceName;
    }

    public void setServiceName(String serviceName) {
        this.serviceName = serviceName;
    }

    public MnsMsgInfo getMnsMsgInfo() {
        return mnsMsgInfo;
    }

    public void setMnsMsgInfo(MnsMsgInfo mnsMsgInfo) {
        this.mnsMsgInfo = mnsMsgInfo;
    }

}
